package com.redoor.app.stake.basicdata.hsf.service.impl;

import com.alibaba.boot.hsf.annotation.HSFProvider;
import com.alibaba.druid.util.StringUtils;
import com.redoor.app.stake.basicdata.model.*;
import com.redoor.app.stake.basicdata.service.BaseStakeService;
import com.redoor.app.stake.basicdata.service.BaseStationService;
import com.redoor.app.stake.basicdata.service.BaseVendorInfoService;
import com.redoor.app.stake.basicdata.service.SyncOperatorService;
import com.redoor.app.stake.common.utils.TimeCalculationUtil;
import com.yotouch.app.stake.Consts;
import com.yotouch.app.stake.StakeConsts;
import com.yotouch.app.stake.hsf.AssetsCenterService;
import com.yotouch.app.stake.model.*;
import com.yotouch.app.stake.model.response.HsfError;
import com.yotouch.app.stake.model.response.ResponseAssetsCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * HSF调用,大屏统计资产统计接口实现类
 * Created by zhangYiHang on 2018/3/27.
 */
@HSFProvider(serviceInterface = AssetsCenterService.class, serviceVersion = "5.0.0", serviceGroup = "grp_asset_of_stake", clientTimeout = 600000)
@Service
public class AssetsCenterServiceImpl implements AssetsCenterService {

    private static final Logger logger = LoggerFactory.getLogger(AssetsCenterServiceImpl.class);

    //充电站service
    @Autowired
    private BaseStationService baseStationService;
    //充电桩service
    @Autowired
    private BaseStakeService baseStakeService;
    //产权单位service
    @Autowired
    private SyncOperatorService syncOperatorService;
    //厂商信息service
    @Autowired
    private BaseVendorInfoService baseVendorInfoService;
    @Autowired
    TimeCalculationUtil timeCalculationUtil;

    /**
     * 大屏接口
     * 查询充电站地理信息包括充电站实时状态、设备状态等信息
     *
     * @param orgType - 层级类型：1国；2省；3市；6：高速（G0：所有高速站点，G[x]单条高速站点）
     * @param orgNo - 区域编码
     * @param stationType - 0：查询所有的，1：国网;2:社会（不含个人共享桩）；3：个人共享
     * @param pageNum - 请求当前页数
     * @param pageSize - 目前按100条记录进行分页
     * @return
     */
    @Override
    public ResponseAssetsCenter getStationGISInfo(int orgType, String orgNo, int stationType, int pageNum, int pageSize) {
        ResponseAssetsCenter rac = new ResponseAssetsCenter() ;
        if(pageNum < 1){
            rac.setCode(1) ;
            rac.setMessage("错误的页码：" + pageNum) ;
            return rac ;
        }

        if(pageSize < 0 || pageSize > 100){
            rac.setCode(1) ;
            rac.setMessage("错误的每页数据量：" + pageSize) ;
            return rac ;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orgType",orgType);
        map.put("orgNo",orgNo);
        map.put("stationType",stationType);
        map.put("offset",(pageNum - 1) * pageSize);
        map.put("limit",pageSize);
        map.put("status",Consts.STATUS_NORMAL);
        //查询对应充电站信息
        List<ChargingMonitor> list = this.baseStationService.qryStationinfoByConditionToHSF(map);
        int total = 0 ;
        //如果结果不为空查询总数量
        if(list != null){
            total = this.baseStationService.qryStationinfoByConditionTotalToHSF(map);
        }
        rac.setCurrentPage(pageNum) ;
        rac.setRecordNums(total) ;
        int maxPage = total / pageSize + (total % pageSize == 0 ? 0 : 1) ;
        rac.setMaxPage(maxPage == 0 ? 1 : maxPage) ;
        rac.setData(list.toArray()) ;

        return rac ;
    }
    /**
     * 大屏调用
     * 获取国网以及第三方桩数目
     * @param orgNo 区域编码
     * @param orgType 层级类型:1国;2省;3市;4站;5桩6、高速
     * @return
     */
    @Override
    public ResponseAssetsCenter getGlobalMonitor(String orgNo, int orgType) {
        logger.info("getGlobalMonitor get orgNo=" + orgNo + " orgType=" + orgType);
        ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter();
        if(StringUtils.isEmpty(orgNo.trim())){
            responseAssetsCenter.setCode(1) ;
            responseAssetsCenter.setMessage("参数错误") ;
            responseAssetsCenter.setError("bad parameter") ;
            return responseAssetsCenter;
        }

        Map<String, Object> map = new HashMap<String, Object>(4);
        map.put("orgNo", orgNo);
        map.put("orgType", orgType);
        GlobalMonitor globalMonitor = this.baseStakeService.qryStakeGlobalMonitorToHSF(map);
        responseAssetsCenter.setData(globalMonitor);
        return responseAssetsCenter;
    }
    /**
     * 大屏调用
     * 获取交直流，公专用桩数目
     * @param orgNo 区域编码
     * @param orgType 层级类型:1国;2省;3市;4站;5桩6、高速
     * @return
     */
    @Override
    public ResponseAssetsCenter getRegionStatistic(String orgNo, int orgType) {
        ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter();
        logger.info("get regionStatistic orgNo=" + orgNo + " orgType = " + orgType);
        if(StringUtils.isEmpty(orgNo.trim())){
            responseAssetsCenter.setCode(1) ;
            responseAssetsCenter.setMessage("参数错误") ;
            responseAssetsCenter.setError("bad parameter") ;
            return responseAssetsCenter ;
        }

        Map<String, Object> map = new HashMap<String, Object>(4);
        map.put("orgNo", orgNo);
        map.put("orgType", orgType);
        RegionStatistic regionStatistic = this.baseStakeService.qryStakeRegionStatisticToHSF(map);
        responseAssetsCenter.setData(regionStatistic);
        return responseAssetsCenter;
    }
    /**
     * 大屏调用
     * 根据充电站标识获取充电站安全运行天数信息
     * @param stationNo 站编码
     * @return
     */
    @Override
    public ResponseAssetsCenter getChargingWorkingInfo(String stationNo) {
        ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter();

        BaseStation baseStation = this.baseStationService.qryStationBySataionNo(stationNo);
        if(baseStation == null){
            responseAssetsCenter.setCode(HsfError.ERROR_CODE_NO_SUCH_STAKE) ;
            responseAssetsCenter.setError(HsfError.ERROR_MSG_NO_SUCH_STAKE) ;
            return responseAssetsCenter;
        }
        ChargingWorkingInfo chargingWorkingInfo = new ChargingWorkingInfo();
        Date rundate = baseStation.getRundate();
        String startAt =null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (rundate != null){
            startAt = df.format(rundate);
        }
        if(!StringUtils.isEmpty(startAt)){
            startAt = startAt.replaceAll("-","") ;
        }
        chargingWorkingInfo.setProductionDay(startAt);
        SyncOperator syncOPerator = this.syncOperatorService.findById(baseStation.getOperatoruuid());
        if(syncOPerator != null){
            chargingWorkingInfo.setManufacturer(syncOPerator.getName());
        }
        try {
            if(baseStation.getRundate()!=null){
                int day = timeCalculationUtil.getDifferenceDays(df.format(baseStation.getRundate()),new Date());
                chargingWorkingInfo.setWorkingDays(day);
            }

        } catch (ParseException e) {
            chargingWorkingInfo.setWorkingDays(0) ;
            responseAssetsCenter.setError(HsfError.ERROR_MSG_DATE_FORMATE);
        }
        responseAssetsCenter.setData(chargingWorkingInfo);
        return responseAssetsCenter;
    }
    /**
     * 大屏调用
     * 根据桩编码获取充电站相关信息
     * @param stakeNo 桩编码
     * @return
     */
    @Override
    public ResponseAssetsCenter getPileMonitor(String stakeNo) {
        logger.info("AssetCenterService getPileMonitor stakeNo='" + stakeNo + "'");
        //根据桩编号查询桩
        Stake baseStake = this.baseStakeService.getStakeHSF(stakeNo);
        if(baseStake == null){
            ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter() ;
            responseAssetsCenter.setCode(HsfError.ERROR_CODE_NO_SUCH_STAKE) ;
            responseAssetsCenter.setError(HsfError.ERROR_MSG_NO_SUCH_STAKE) ;
            return responseAssetsCenter;
        }
        PileMonitor pileMonitor = new PileMonitor();
        Calendar createdAt= (Calendar)baseStake.getCreatedAt();
        //createdAt
        if(createdAt != null){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd") ;
            pileMonitor.setCreateTime(formatter.format(createdAt.getTime())) ;
        }
        //查询厂商信息
        Vendor vendor = baseStake.getVendor();
        pileMonitor.setDicFactory(vendor==null?"":vendor.getName());
        //TODO
        if(baseStake.getMaxOutVolt() == null  || baseStake.getPower() == null || baseStake.getMaxOutVolt() == 0){
            pileMonitor.setMaxOutCurrent("0");
        }else{
            try {
                Double power = baseStake.getPower();
                double p = power.doubleValue();
                Integer u = baseStake.getMaxOutVolt().intValue();
                double i = p*1000/u;
                pileMonitor.setMaxOutCurrent(new DecimalFormat("#.00").format(i)+"");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //pileMonitor.setMaxOutCurrent("100");
        //pileMonitor.setMinOutVolt("220");
        pileMonitor.setMaxOutVolt(baseStake.getMaxOutVolt() + "") ;
        pileMonitor.setOrgNo(baseStake.getPrOrgName());
        pileMonitor.setPower(baseStake.getPower() + "") ;
        if(baseStake.getType()!=null) {
            pileMonitor.setChargingType((Integer) baseStake.getType()==1?2:
                    ((Integer) baseStake.getType()==2?1:0));
        }
        ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter();
        responseAssetsCenter.setData(pileMonitor);
        return responseAssetsCenter;
    }
    /**
     * 大屏调用
     * @param gsNo 高速编号,高速公路查询时全局传G0
     * @return
     */
    @Override
    public ResponseAssetsCenter getHighWayRegion(String gsNo) {
        List<BaseStation> baseStationCount = this.baseStationService.qryStationBygsNo(gsNo);
        int stations = 0;
        if(baseStationCount != null){
            stations = baseStationCount.size();
        }

        int miles = stations * 49 ;
        int cities = (int)(stations * 0.219) ;

        HighWayRegion highWayRegion = new HighWayRegion() ;
        highWayRegion.setCoverCity(cities) ;
        highWayRegion.setCoverCount(stations) ;
        highWayRegion.setCoverDistance(miles) ;

        ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter();
        responseAssetsCenter.setData(highWayRegion);
        return responseAssetsCenter;
    }
    /**
     * 大屏调用
     * @return
     */
    @Override
    public ResponseAssetsCenter getSocialPileRank() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", Consts.STATUS_NORMAL);
        map.put("orgType", null);
        map.put("orgNO", null);
        //社会运营
        //String sociaSql = " isThird not in (0,1) and stakeStatus not in (11) and status="+StakeConsts.STATUS_NORMAL;
        SocialPile socialPile = this.baseStakeService.qryBaseStakeCount(map);

        //社会充电桩排名 （排名前8个）
        //传入空值条件(共用方法)
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("orgType", null);
        map1.put("orgNO", null);
        List<EChartsData> eChartsData = this.baseStakeService.qryEChartsData(map1);
        int otherTotal = 0;
        for (EChartsData echarts:eChartsData) {
            otherTotal += echarts.getValue();
        }
        EChartsData other = new EChartsData() ;
        int otherNumber = socialPile.getSocialTotal() - otherTotal - socialPile.getSouthNetCount() ; //计算其他数量，社会总数 - 前7个的总数
        other.setValue(otherNumber) ;
        other.setName("其他") ;
        eChartsData.add(other);
        socialPile.setSocialRank(eChartsData.toArray(new EChartsData[0])) ;
        ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter();
        responseAssetsCenter.setData(socialPile);
        return responseAssetsCenter;
    }

    @Override
    public ResponseAssetsCenter getProvinceSocialPileRank(String orgNO, int orgType) {
        ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter();
        if(orgNO==null || orgNO.trim().length()==0){
            orgNO = "100000";// 区域编码默认为100000：全国
        }
        if(orgType==1){
            orgNO = "100000";// 区域编码默认为100000：全国
        }else{
            responseAssetsCenter.setCode(1);
            responseAssetsCenter.setError(HsfError.ERROR_MSG_BAD_PARAMETER);
            responseAssetsCenter.setMessage("请传入正确的层级!");
            return responseAssetsCenter;
        }
        Map<String, Object> wheres = new HashMap<String, Object>();
        wheres.put("orgType", orgType);
        wheres.put("orgNO", orgNO);
        wheres.put("status", Consts.STATUS_NORMAL);

        SocialPile socialPile = this.baseStakeService.qryBaseStakeCount(wheres);

        //operator type 2.南方电网 59.其他第三方
        List<EChartsData> eChartsData = this.baseStakeService.qryEChartsData(wheres);
        int otherTotal = 0 ;
        for (EChartsData echart:eChartsData) {
            otherTotal += echart.getValue();
        }
        EChartsData other = new EChartsData() ;
        int otherNumber = socialPile.getSocialTotal() - otherTotal - socialPile.getSouthNetCount() ; //计算其他数量，社会总数 - 前7个的总数
        other.setValue(otherNumber) ;
        other.setName("其他") ;
        eChartsData.add(other);
        socialPile.setSocialRank(eChartsData.toArray(new EChartsData[0])) ;

        responseAssetsCenter.setData(socialPile);
        return responseAssetsCenter;
    }
    //TODO 需要处理直辖市，去掉第二级
    @Override
    public ResponseAssetsCenter getCitysStationInfo(String orgNo, int orgType, int queryType) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orgNo", orgNo);
        map.put("orgType", orgType);
        map.put("queryType", queryType);
        map.put("status", Consts.STATUS_NORMAL);
        //分组条件
        String groupByType = "city";
        //对象是否为直辖市
        if(this.isSpecialCity(orgNo)){
            groupByType = "dis";
        }
        map.put("groupByType", groupByType);
        //查询对象集合
        List<CityData> districts = this.baseStationService.qryCitysStationInfo(map);
        ResponseAssetsCenter responseAssetsCenter = new ResponseAssetsCenter();
        responseAssetsCenter.setData(districts.toArray()) ;
        return responseAssetsCenter;
    }
//    /**
//     * 此方法原代码中未被调用,返回结果为stake集合
//     * @Author zhangYiHang
//     * @Date 2018/3/29 10:20
//     * @Param
//     */
//    List<BaseStake> findEntityList(String orgNo, int orgType, boolean isThird){
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("orgNo", orgNo);
//        map.put("orgType", orgType);
//        map.put("isThird", isThird);
//        map.put("status", Consts.STATUS_NORMAL);
//        List<BaseStake> list = this.baseStakeService.qryBaseStakeList(map);
//        return list;
//    }

    /**
     * 检测是否是直辖市
     *
     * @return
     */
    private boolean isSpecialCity(String provinceCode){
        return "110000".equals(provinceCode) || "120000".equals(provinceCode)
                || "500000".equals(provinceCode) || "310000".equals(provinceCode) ;
    }
}
